package com.smart.common.security;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 配置security的认证管理器
 *
 * @author arnold.zhao
 * @date 2018/10/15 14:27
 */
public class AuthenticationProvider implements org.springframework.security.authentication.AuthenticationProvider {

    /**
     * @Description: 主要用于校验登录用户的合法性
     * @Param: [authentication]
     * @return: org.springframework.security.core.Authentication
     * @Author: Arnold.zhao
     * @Date: 2018/10/17
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        //authentication.getName()获取当前登录账户；
        authentication.getName();
        //前端Md5尽可能先做加密后，再后端校验，（此时无需再次Md5转换）
        String rawPass = (String) authentication.getCredentials(); //登录的明文密码
        //UserDetails userDetails = UserService.logUserName(authentication.getName(),rawPass);

        UserDetails userDetails = null;
        userDetails = new org.springframework.security.core.userdetails.User("user.getId()", "user.getPassword()",
                true, true, true, true, AuthorityUtils.createAuthorityList("ROLE_USER"));

        //表示账号不存在
        if (userDetails == null) return null;

        //账号存在，则返回 Authentication
        UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails, authentication.getCredentials(), userDetails.getAuthorities());

        return usernamePasswordAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return true;
    }
}
